/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:42
 */

package com.lenovo.mso2o.service;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.util.DLog;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.biz.AccountManagerImpl;
import com.lenovo.mso2o.ui.MainActivity;

import java.util.Calendar;
import java.util.List;

public class TickNetworkReceiver extends BroadcastReceiver {

    public static void restartIfNecessary(final Context context) {

        if (AccountManagerImpl.instance.isLogin()) {
            if (UploadService.shouldRestart()) {
                DLog.w("upload:", "upload: restarting");
                UploadService.actionStart(context);
            }
            if(MSApplication.isActivityVisible()) {
                boolean active = false;
                List<Activity> activities = FBaseActivity.getActivites();
                if(activities.size() > 0) {
                    Activity curr = activities.get(activities.size() - 1);
                    if (curr instanceof MainActivity && ((MainActivity) curr).currIdx() == 1) {
                        AutoSignService.setDurationIfChanged(10);
                        active = true;
                    }
                }
                if(!active)
                    AutoSignService.setDurationIfChanged(30);
            }else{
                if(activeDuration(System.currentTimeMillis())){
                    AutoSignService.setDurationIfChanged(300);
                }else{
                    AutoSignService.setDurationIfChanged(600);
                }
            }
        }
    }

    public static boolean activeDuration(long millis){
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis(millis);
        if(now.get(Calendar.HOUR_OF_DAY) > 6 && now.get(Calendar.HOUR_OF_DAY) < 24){
            return true;
        }
        return  false;
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        DLog.w("network:", "login:" + AccountManagerImpl.instance.isLogin());
        restartIfNecessary(context);
    }

    /**
     * 1 minute receive, backup plan for service killing
     */
    public static class TickReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) {
                DLog.w("tick:", "login:" + AccountManagerImpl.instance.isLogin());
                restartIfNecessary(context);
            }
        }
    }
}

